<?php namespace App\Http\Controllers\Api;

use App\Exceptions\SecurityException;
use App\Files;
use App\Http\Controllers\Controller;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Illuminate\Http\Request;
use App\Http\Requests\SignUpRequest;
use App\Images;
use App\Services\FileManager;
use App\Services\Tools;
use App\Services\UserManager;
use App\Services\Wechat\WechatLogin;
use App\Services\YunPian;
use App\User;
use App\UserInfo;
use App\VerifyCodeByPhone;
use Carbon\Carbon;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Input;
use Auth;
use Hash;
use Session;
use Log;
use Cookie;

class AuthController extends ApiController
{

    public function signOut(Guard $guard){
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $guard->logout();

        return response()->json(["level"=>"success","message"=>"退出登陆成功"]);
    }

    public function SignIn(){
        $loginId  = input::get('login_id');
        $username = input::get('username');
        $email    = input::get('email');
        $phone    = input::get('phone');
        $password = input::get('password');

        if($phone){
            $user = UserManager::signInByPhone($phone,$password,1);
        }elseif($email){
            $user = UserManager::signInByEmail($email,$password,1);
        }elseif($username){
            $user = UserManager::signInByUsername($username,$password,1);
        }else{
            if(Tools::isEmail($loginId))
                $user = UserManager::signInByEmail($loginId,$password,1);
            else if(Tools::isPhone($loginId))
                $user = UserManager::signInByPhone($loginId,$password,1);
            else
                $user = UserManager::signInByUsername($loginId,$password,1);
        }

        return $this->buildResponse(trans('登录成功！'),$user);
    }

    public function weixinLogin(){
        $state = Input::get('state');

        $state = !is_null($state) ? $state : 0;
        $callbackUrl = route('Api.Auth.weixinCallback');
        $url         = WechatLogin::buildRedirectUrl($callbackUrl,$state);
        return redirect($url);
    }

    public function weixinCallback(){
        $code       = Input::get('code');
        $state      = Input::get('state');

        /** @var  WechatLogin $result */
        $result = WechatLogin::getWechatUserInfo($code);

        $accessToken = $result->getAccessToken();
        $openId      = $result->getOpenId();
        $nickname    = $result->getNickname();
        $sex         = $result->getSex();
        $headImgUrl  = $result->getHeadimgurl();
        $province    = $result->getProvince();
        $city        = $result->getCity();
        $unionid     = $result->getUnionid();

        /** @var  User $userModel */
        $userModel = User::whereOpenid($openId)->first();

        $userType = 0;
        switch($state){
            case 'usercenter':
                $userType=0;
                break;
            case 'docUserCenter':
                $userType = 1;
                break;
        }
//        if($userModel){
//            Auth::login($userModel,1);

        if(!$userModel){
            $userModel = new User();
            $userModel->openid   = $openId;
            $userModel->password = bcrypt('123456');
//            $userModel->reg_ip   = \Input::ip();
            $userModel->reg_time = Carbon::now();
            $userModel->role     = $userType;
            $userModel->save();

            $userModel->user_key = md5($userModel->password.$userModel->id.rand(1000,9999).time());
            $userModel->save();


            $userInfo = new UserInfo();
            $userInfo->user_id = $userModel->id;
            $userInfo->nick    = $nickname;
            $userInfo->sexual  = $sex;
            $userInfo->province = $province;
            $userInfo->city     = $city;
            $userInfo->save();

            /** @var Files $fileModel */
            $fileModel = FileManager::saveFileByWechatImg($headImgUrl);
            if($fileModel){
                $imageModel = Images::whereFileId($fileModel->id)->first();
                if(!$imageModel){
                    $imageModel = new Images();
                    $imageModel->file_id = $fileModel->id;
                    $imageModel->img_name= 'wechat_img';
                    $imageModel->img_type= $fileModel->file_type;
                    $imageModel->save();

                    $userInfo->portrait_id = $imageModel->id;
                    $userInfo->save();
                }else{
                    $userInfo->portrait_id = $imageModel->id;
                    $userInfo->save();
                }
            }

//            Auth::login($userModel,1);
        }else{
            if(is_null($userModel->user_key) || $userModel->user_key == ''){
                $userModel->user_key = md5($userModel->password.$userModel->id.rand(1000,9999).time());
                $userModel->save();
            }

            $thisUserInfo = UserInfo::whereUserId($userModel->id)->first();
            if(!$thisUserInfo){
                $thisUserInfo = new Userinfo();
                $thisUserInfo->user_id = $userModel->id;
                $thisUserInfo->nick    = $nickname;
                $thisUserInfo->sexual  = $sex;
                $thisUserInfo->province = $province;
                $thisUserInfo->city     = $city;
                $thisUserInfo->save();
            }

            /** @var Files $fileModel */
            $fileModel = FileManager::saveFileByWechatImg($headImgUrl);
            if($fileModel){
                $imageModel = Images::whereFileId($fileModel->id)->first();
                if(!$imageModel){
                    $imageModel = new Images();
                    $imageModel->file_id = $fileModel->id;
                    $imageModel->img_name= 'wechat_img';
                    $imageModel->img_type= $fileModel->file_type;
                    $imageModel->save();

                    $thisUserInfo->portrait_id = $imageModel->id;
                    $thisUserInfo->save();
                }else{
                    $thisUserInfo->portrait_id = $imageModel->id;
                    $thisUserInfo->save();
                }
            }
        }

        $open = CryptoJSAES::encrypt("wx_openid@".$userModel->openid,env('AES_KEY'));
        $cookie = Cookie::forever("user_token",$open);

        switch($state){
            case 'usercenter':
                $url = route('M.Home.newUserCenter');
                break;
            case 'docUserCenter':
                $url = route('M.Doctor.userCenter');
                break;
            case 'doctordetail':
                $url = route('M.Home.newDoctorList');
                break;
            case 'followDoctor':
                $url = route('M.Home.newFollowDoctors');
                break;
            case 'packages':
                $url = route('M.Home.packages');
                break;
            case 'meeting':
                $url = 'http://meeting.51wenyisheng.com/#/';
                break;
            default:
                $url = route('M.Home.index');
                break;
        }

        return redirect()->to($url)->cookie($cookie);
    }

    public function signInByAdmin(){
        $username = Input::get('username');
        $password = Input::get('password');

        /** @var User $thatUsers */
        $thatUsers = User::whereUsername($username)->first();
        if((int)$thatUsers->role < 999)
            throw new SecurityException(SecurityException::NoPermission);

        UserManager::signInByUsername($username,$password,true);

        $openid = $thatUsers->user_key;

        $open = CryptoJSAES::encrypt("wx_openid@".$openid,env('AES_KEY'));
        $cookie = Cookie::forever("user_token",$open);

        return response()->json(["level"=>'success',"message"=>"登录成功","data"=>$thatUsers])->withCookie($cookie);
    }

    public function changePassword(Guard $guard,Request $request)
    {
        $user = UserManager::isLogin($request);
        if(!$user){
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        }

        $oldPassword = Input::get('oldpassword');
        $newpassword = Input::get('newpassword');

        if(!Hash::check($oldPassword,$user->password))
            throw new SecurityException(SecurityException::PasswordNotMatch);

        $user->password = bcrypt($newpassword);
        $user->save();

        $guard->logout();

        return response()->json(["level"=>'success',"message"=>"修改密码成功","data"=>$user]);
    }
}